/**
 * 
 */
package com.db.stockexchange.server.connection;

import java.io.IOException;
import java.net.ServerSocket;

/**
 * @author Rayman
 * Listen server socket for new connecton from clients
 */
public class ConnectionListener implements Runnable {
	private static final int BACKLOG = 10;
	//private static final int TIMEOUT = 10000;
	
	ServerSocket socket;
	ConnectionPool pool;
	volatile boolean working;
	
	public ConnectionListener(int port, ConnectionPool pool) throws IOException {
		socket = new ServerSocket(port, BACKLOG);		
		this.pool = pool;
		working = true;
	}
	
	public void close() {
		working = false;
		try {
			socket.close();
		} catch (IOException e) {
			System.out.println("Exception occurs while closing server socket: " + e.getMessage());
		}
		pool.close();
	}

	@Override
	public void run() {
		while (working) {
			try {
				pool.add(socket.accept());				
			} catch (IOException e) {
				if (working)
					System.out.println(e.getMessage());
			}
		}
	}
}
